from sqlalchemy import Column, Integer, String, Text, DateTime, JSON,BigInteger,Date
from sqlalchemy.sql import func
from db.database import Base
import hashlib
import uuid
import secrets
from utils.snowflake import snowflake

class UserModel(Base):
    __tablename__ = "user"

    # 组件自增id 使用雪花算法
    id = Column(String(36), primary_key=True, default=lambda: str(uuid.uuid4()))
    remark = Column(Text, nullable=True)
    is_admin = Column(Integer,  default=0 )
    username = Column(String(50), nullable=False)
    real_name = Column(String(50),  nullable=True )
    password = Column(String(255), nullable=False)
    avatar = Column(String(255), nullable=True)
    salt = Column(String(100),  nullable=True )
    last_login_ip = Column(String(100),  nullable=True )
    login_count = Column(Integer,  default=0 )
    last_login_time = Column(DateTime(timezone=True), server_default=func.now())
    email = Column(String(100), unique=True, nullable=True )
    phone = Column(String(20),  nullable=True )
    gender = Column(Integer,  default=0 )
    birthday = Column(Date(),  nullable=True )
    status = Column(Integer, default= 1)
    create_by = Column(String(36), nullable=True, default=None)
    update_by = Column(String(36), nullable=True, default=None)
    create_time = Column(DateTime(timezone=True), server_default=func.now())
    update_time = Column(DateTime(timezone=True), server_default=func.now())
    deleted_at = Column(DateTime(timezone=True), server_default=func.now())
    
    def set_password(self, password):
        """生成盐值并加密密码"""
        self.salt = secrets.token_hex(16)  # 生成随机盐值
        self.password = self._hash_password(password, self.salt)
    
    def check_password(self, password):
        """验证密码是否正确"""
        return self.password == self._hash_password(password, self.salt)
    
    @staticmethod
    def _hash_password(password: str, salt: str) -> str:
        """使用SHA-256加盐哈希密码"""
        salted_password = password + salt
        return hashlib.sha256(salted_password.encode('utf-8')).hexdigest()
